package com.ruoyi.web.controller.teaching;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.teaching.domain.TeachingClasses;
import com.ruoyi.teaching.domain.TeachingClassesStudents;
import com.ruoyi.teaching.domain.TeachingStudent;
import com.ruoyi.teaching.service.ITeachingClassesService;
import com.ruoyi.teaching.service.ITeachingClassesStudentsService;
import com.ruoyi.teaching.service.ITeachingCourseFolderService;
import com.ruoyi.teaching.service.ITeachingStudentService;
import com.ruoyi.web.controller.teaching.WebSocket.LessonWebSocket;
import net.sf.ehcache.event.CacheEventListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 准备上课
 *
 * @author William
 */
@Controller
@RequestMapping("/teaching/lesson")
public class TeachingTakeLesson extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ITeachingStudentService studentService;
    @Autowired
    private ITeachingClassesService classesService;
    @Autowired
    private ITeachingClassesStudentsService classesStudentsService;

    @Autowired
    private ITeachingCourseFolderService folderService;

    private String prefix = "teaching/lesson";

    @PostMapping("/call/{classId}")
    @ResponseBody
    public AjaxResult call(@PathVariable("classId") Long classId, @RequestBody String notice) {
        TeachingClasses classes = classesService.selectTeachingClassesByClassId(classId);
        TeachingClassesStudents param = new TeachingClassesStudents();
        List<TeachingClassesStudents> students = classesStudentsService.selectTeachingClassesStudentsList(param);

        Long[] userIds = students.stream().map(a -> a.getUserId()).toArray(Long[]::new);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action", "lesson");
        jsonObject.put("userIds", userIds);
        jsonObject.put("data", classes);
        jsonObject.put("notice", notice);
        jsonObject.put("sendBy", getUserId());


        try {
            LessonWebSocket.sendInfo(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success("发送成功");
//        return prefix + "/lesson";
    }

    @PostMapping("/echo/{classId}/{teacherId}")
    @ResponseBody
    public AjaxResult echo(@PathVariable("classId") Long classId, @PathVariable("teacherId") Long teacherId) {
//        TeachingClasses classes = classesService.selectTeachingClassesByClassId(classId);
//        TeachingClassesStudents param = new TeachingClassesStudents();
//        List<TeachingClassesStudents> students = classesStudentsService.selectTeachingClassesStudentsList(param);
//        students = students.stream().filter(a -> a.getClassId().equals(classId) && a.getUserId().equals(getUserId())).collect(Collectors.toList());
//        TeachingClassesStudents classesStudent = students.get(0);
        TeachingStudent student = studentService.selectTeachingStudentByUserId(getUserId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action", "lessonEcho");
        jsonObject.put("userIds", new Long[]{teacherId});
        jsonObject.put("data", student);
        jsonObject.put("sendBy", getUserId());

        try {
            LessonWebSocket.sendInfo(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success("发送成功");
//        return prefix + "/lesson";
    }

    @PostMapping("/startLesson/{classId}")
    @ResponseBody
    public AjaxResult startLesson(@PathVariable("classId") Long classId) {

        TeachingClasses classes = classesService.selectTeachingClassesByClassId(classId);
        if (StringUtils.isNull(classes)) {
            return error("班级不存在");
        }
        //结束上课需要判断该班级是否已在上课
        if (classes.getLessonStatus().equals(1)) {
            return error("此班级已经开始上课，无法操作此按钮");
        }
        classes.setLessonStatus("1");
        return toAjax(classesService.updateTeachingClasses(classes));
    }

    @PostMapping("/finishLesson/{classId}")
    @ResponseBody
    public AjaxResult finishLesson(@PathVariable("classId") Long classId) {

        TeachingClasses classes = classesService.selectTeachingClassesByClassId(classId);
        if (StringUtils.isNull(classes)) {
            return error("班级不存在");
        }
        //结束上课需要判断该班级是否已在上课
        if (classes.getLessonStatus().equals(0)) {
            return error("此班级还没有开始上课,无需结束");
        }
        int needFolderCount = classes.getNeedFolderCount() + 1;
        //新增班级时候需要设置默认需要的章节数量
        String ancestors = folderService.getNeedSections(classes.getCourseId(), needFolderCount);
        classes.setCurrentFolderAncestors(ancestors);
        classes.setNeedFolderCount(needFolderCount);
        classes.setLessonStatus("0");
        int currentFolderIndex = classes.getCurrentFolderIndex() + 1;
        Long folderId = folderService.getCurrentFolderId(classes.getCourseId(), currentFolderIndex);
        if (folderId > 0) {
            classes.setCurrentFolderIndex(currentFolderIndex);
            classes.setCurrentFolderId(folderId);
        }
        return toAjax(classesService.updateTeachingClasses(classes));
    }
}
